package cn.mymall.web.controller.houtai.mall;

import cn.mymall.constant.MallConstant;
import cn.mymall.constant.StatusConstant;
import cn.mymall.entity.mall.*;
import cn.mymall.service.IProvinceService;
import cn.mymall.service.mall.*;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BaseWebUtil;
import cn.mymall.util.BeanUtil;
import cn.mymall.util.BindUtils;
import cn.mymall.util.DateUtil;
import cn.mymall.vo.product.ProductSearchResultVo;
import cn.mymall.vo.product.ProductSearchVo;
import cn.mymall.web.controller.houtai.BaseHoutaiController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProductApiController extends BaseHoutaiController {
	@Autowired
	private IProductService productService;
	@Autowired
	private IVendorService vendorService;
	@Autowired
	private IShipperService shipperService;
	@Autowired
	private ICategoryService categoryService;
	@Autowired
	private ISubCategoryService subCategoryService;
	@Autowired
	private ISkuService skuService;
	@Autowired
	private IPictureService pictureService;
	@Autowired
	private IProvinceService provinceService;;
	@Autowired
	private IShippingTemplateService shippingTemplateService;

	// 列表
	@RequestMapping("/api/product/list")
	public ResultCode list(Integer pagenum, Integer pagesize, ProductSearchVo searchVo) {
		if(pagenum==null){
			pagenum = 1;
		}
		if(pagesize==null){
			pagesize = 10;
		}
		searchVo.setPageNo(pagenum);
		searchVo.setPageSize(pagesize);
		Page<Product> page = productService.getProductList(searchVo);
		List<Product> list = page.getRecords();
		List<ProductSearchResultVo> searchResultVoList = new ArrayList<>();
		for(Product product : list){
			ProductSearchResultVo resultVo = new ProductSearchResultVo();
			BeanUtil.copyProperties(resultVo, product);
			Vendor vendor = vendorService.getById(product.getVendorId());
			Category category = categoryService.getById(product.getCategoryId());
			SubCategory subCategory = subCategoryService.getById(product.getSubCategoryId());
			resultVo.setVendorName(vendor.getVendorName());
			resultVo.setCategoryName(category.getName());
			resultVo.setSubCategoryName(subCategory.getName());
			resultVo.setOffSaleDate(DateUtil.formatDate(product.getOffSaleTime()));
			resultVo.setPictureNum(pictureService.count(new QueryWrapper<Picture>().eq("product_id", product.getId())));
			resultVo.setSkuNum(skuService.count(new QueryWrapper<Sku>().eq("product_id", product.getId()).eq("status", StatusConstant.Y)));
			searchResultVoList.add(resultVo);
		}
		Map map = new HashMap<>();
		map.put("productList", searchResultVoList);
		map.put("page", ImmutableMap.of("total", page.getTotal(), "pagenum", page.getCurrent()));
		return ResultCode.getSuccessReturn(map);
	}

	// 新增or修改
	@RequestMapping("/api/product/get")
	public ResultCode get(Integer id) {
		Product product = new Product();
		if (id != null) {
			product = productService.getById(id);
		}
		Map map = new HashMap<>();
		map.put("product", product);
		map.put("categoryList", categoryService.list());
		map.put("vendorList", vendorService.list());
		map.put("shipperList", shipperService.list());
		map.put("shippingTemplateList", shippingTemplateService.list());
		map.put("provinceList", provinceService.list());
		return ResultCode.getSuccessReturn(map);
	}

	// 保存
	@RequestMapping("/api/product/save")
	public ResultCode<Product> save(Integer id) {
		Product product = null;
		if (id != null) {
			product = productService.getById(id);
		} else {
			product = new Product();
		}
		BindUtils.bindData(product, BaseWebUtil.getRequestParams());
		if(StringUtils.isBlank(product.getName())) {
			return ResultCode.getFailure("请输入商品名称");
		}
		if(StringUtils.isBlank(product.getTingsType())){
			product.setTingsType(MallConstant.TINGS_TYPE_ENTITY);
		}
		if(StringUtils.equals(product.getTingsType(), MallConstant.TINGS_TYPE_ENTITY)){
			product.setElecBatchId(null);
		}
		if(StringUtils.equalsIgnoreCase(product.getTingsType(), MallConstant.TINGS_TYPE_ELEC) && product.getElecBatchId()==null){
			return ResultCode.getFailure("电子类商品需要选择电子码");
		}

		if(StringUtils.isNotBlank(product.getRelateProductIds())) {
			String relateProductIds = product.getRelateProductIds().trim().replace("，", ",");
			List<Integer> relateProductIdList = BeanUtil.getIdList(relateProductIds);
			for (Integer relateProductId : relateProductIdList) {
				Product relateProduct = productService.getById(relateProductId);
				if (relateProduct == null || !relateProduct.hasBooking()) {
					return ResultCode.getFailure("关联商品已下架，不能购买："+relateProductId);
				}
				List<Sku> skuList = skuService.findBookingByProductId(relateProductId);
				if (CollectionUtils.isEmpty(skuList)) {
					return ResultCode.getFailure("关联商品SKU库存不足："+relateProductId);
				}
				Sku sku = skuList.get(0);
				if (!sku.hasStock()) {
					return ResultCode.getFailure("关联商品库存不足：" + relateProductId);
				}
			}
			product.setRelateProductIds(relateProductIds);
		}
		productService.saveOrUpdate(product);
		return ResultCode.SUCCESS;
	}

	@RequestMapping("/api/product/setStatus")
	public ResultCode setStatus(Integer id, String status) {
		Product product = productService.getById(id);
		if(StringUtils.equals(status, MallConstant.SKU_STATUS_ON_SALE)){
			int count = pictureService.countByProductId(id);
			if(count==0){
				return ResultCode.getFailure("图片还没有设置，不能上线商品");
			}
			List<Sku> skuList = skuService.findBookingByProductId(id);
			if(CollectionUtils.isEmpty(skuList)){
				return ResultCode.getFailure("没有可用的sku不能上线商品，不能上线商品");
			}
		}
		product.setStatus(status);
		productService.updateById(product);

		return ResultCode.SUCCESS;
	}

	@RequestMapping("/api/product/setSortNo")
	public ResultCode setStatus(Integer id, Integer sortNo) {
		if(sortNo==null) {
			sortNo = 1;
		}
		Product product = productService.getById(id);
		product.setSortNo(sortNo);
		productService.updateById(product);
		return ResultCode.SUCCESS;
	}

	@RequestMapping("/api/product/listByIds")
	public ResultCode listByIds(String productIds) {
		List<Map> productList = new ArrayList<>();
		if(StringUtils.isBlank(productIds)){
			return ResultCode.getSuccessReturn(productList);
		}
		List<Integer> productIdList = BeanUtil.getIdList(productIds);
		for (Integer productId : productIdList) {
			Product product = productService.getById(productId);
			Map map = ImmutableMap.of("id", productId,"name", product.getName());
			productList.add(map);
		}
		return ResultCode.getSuccessReturn(productList);
	}

	@RequestMapping("/api/product/listByName")
	public ResultCode listByName(String name) {
		ProductSearchVo searchVo = new ProductSearchVo();
		searchVo.setName(name);
		searchVo.setPageNo(1);
		searchVo.setPageSize(20);
		Page<Product> page = productService.getProductList(searchVo);
		List<Map> productList = new ArrayList<>();
		for (Product product : page.getRecords()) {
			Map map = ImmutableMap.of("id", product.getId(),"name", product.getName());
			productList.add(map);
		}
		return ResultCode.getSuccessReturn(productList);
	}
}
